package Servidor;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import Ventanas.admin.PanelInicialA;
import util.GetFrame;
import util.SocketManager;

public class Server {

	private ServerSocket server;
	private Socket socket;
	private SocketManager manager;
	private Peticion request;
	PanelInicialA panel;

	public Server(int puerto, PanelInicialA panel) {
		this.panel = panel;
		try {
			server = new ServerSocket(puerto);
		} catch (IOException e) {
			e.printStackTrace();
		}
		escuchar();
	}

	public void escuchar() {
		while (true) {
			if (panel.getSockets().size() < GetFrame.getVentanaA(panel)
					.getMaximoConexiones()) {
				try {
					socket = server.accept();
					manager = new SocketManager(socket);
					if (panel.getSockets().size() > GetFrame.getVentanaA(panel)
							.getMaximoConexiones()) {
						System.out.println("Limite de usuarios superado.");

						manager.CerrarStreams();
						manager.CerrarSocket();
					}

					else

					{
						System.out.println(GetFrame.getVentanaA(panel)
								.getMaximoConexiones());
						System.out.println("Manager Creado.");
						panel.insertarSocket(manager);
						System.out.println("Num Usuarios: "
								+ panel.getSockets().size());
						request = new Peticion(manager);
						Thread hilo = new Thread(request);
						hilo.start();
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}

		}
	}
}
